package org.github.foxnic.web.system.controller;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.github.foxnic.api.error.ErrorDesc;
import com.github.foxnic.api.transter.Result;
import com.github.foxnic.api.validate.annotations.NotNull;
import com.github.foxnic.commons.io.StreamUtil;
import com.github.foxnic.dao.data.PagedList;
import com.github.foxnic.dao.data.SaveMode;
import com.github.foxnic.dao.excel.ExcelWriter;
import com.github.foxnic.dao.excel.ValidateResult;
import com.github.foxnic.springboot.web.DownloadUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.github.foxnic.web.domain.system.Config;
import org.github.foxnic.web.domain.system.Profile;
import org.github.foxnic.web.domain.system.ProfileVO;
import org.github.foxnic.web.domain.system.meta.ProfileVOMeta;
import org.github.foxnic.web.framework.sentinel.SentinelExceptionUtil;
import org.github.foxnic.web.framework.web.SuperController;
import org.github.foxnic.web.proxy.system.ProfileServiceProxy;
import org.github.foxnic.web.system.service.IConfigService;
import org.github.foxnic.web.system.service.IProfileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  接口控制器
 * </p>
 * @author 李方捷 , leefangjie@qq.com
 * @since 2021-12-03 13:54:38
 * @version
*/

@Api(tags = "sys_profile")
@ApiSort(0)
@RestController("SysProfileController")
public class ProfileController extends SuperController {

	@Autowired
	private IProfileService profileService;

	@Autowired
	private IConfigService configService;


	/**
	 * 添加sys_profile
	*/
	@ApiOperation(value = "添加sys_profile")
	@ApiImplicitParams({
		@ApiImplicitParam(name = ProfileVOMeta.ID , value = "ID" , required = true , dataTypeClass=String.class , example = "default"),
		@ApiImplicitParam(name = ProfileVOMeta.NAME , value = "名称" , required = false , dataTypeClass=String.class , example = "默认"),
		@ApiImplicitParam(name = ProfileVOMeta.NOTES , value = "备注" , required = false , dataTypeClass=String.class , example = "默认 Profile 请勿删除"),
	})
	@ApiOperationSupport(order=1)
	@SentinelResource(value = ProfileServiceProxy.INSERT , blockHandlerClass = { SentinelExceptionUtil.class } , blockHandler = SentinelExceptionUtil.HANDLER )
	@PostMapping(ProfileServiceProxy.INSERT)
	public Result insert(ProfileVO profileVO) {
		Result result=profileService.insert(profileVO,false);
		return result;
	}



	/**
	 * 删除sys_profile
	*/
	@ApiOperation(value = "删除sys_profile")
	@ApiImplicitParams({
		@ApiImplicitParam(name = ProfileVOMeta.ID , value = "ID" , required = true , dataTypeClass=String.class , example = "default")
	})
	@ApiOperationSupport(order=2)
	@NotNull(name = ProfileVOMeta.ID)
	@SentinelResource(value = ProfileServiceProxy.DELETE , blockHandlerClass = { SentinelExceptionUtil.class } , blockHandler = SentinelExceptionUtil.HANDLER )
	@PostMapping(ProfileServiceProxy.DELETE)
	public Result deleteById(String id) {
		List<Config> list=configService.queryList("profile_id=?",id);
		if(!list.isEmpty()) {
			return ErrorDesc.failure().message("当前 Profile 下包含参数，不允许删除");
		}
		Result result=profileService.deleteByIdPhysical(id);
		return result;
	}


	/**
	 * 批量删除sys_profile <br>
	 * 联合主键时，请自行调整实现
	*/
	@ApiOperation(value = "批量删除sys_profile")
	@ApiImplicitParams({
		@ApiImplicitParam(name = ProfileVOMeta.IDS , value = "主键清单" , required = true , dataTypeClass=List.class , example = "[1,3,4]")
	})
	@ApiOperationSupport(order=3)
	@NotNull(name = ProfileVOMeta.IDS)
	@SentinelResource(value = ProfileServiceProxy.DELETE_BY_IDS , blockHandlerClass = { SentinelExceptionUtil.class } , blockHandler = SentinelExceptionUtil.HANDLER )
	@PostMapping(ProfileServiceProxy.DELETE_BY_IDS)
	public Result deleteByIds(List<String> ids) {
		if(ids.equals(IConfigService.DEFAULT_PROFILE_ID)) {
			return ErrorDesc.failure().message("不允许删除默认的 Profile");
		}
		for (String id : ids) {
			List<Config> list=configService.queryList("profile_id=?",id);
			if(!list.isEmpty()) {
				return ErrorDesc.failure().message("Profile 下包含参数，不允许删除");
			}
		}
		Result result=profileService.deleteByIdsPhysical(ids);
		return result;
	}

	/**
	 * 更新sys_profile
	*/
	@ApiOperation(value = "更新sys_profile")
	@ApiImplicitParams({
		@ApiImplicitParam(name = ProfileVOMeta.ID , value = "ID" , required = true , dataTypeClass=String.class , example = "default"),
		@ApiImplicitParam(name = ProfileVOMeta.NAME , value = "名称" , required = false , dataTypeClass=String.class , example = "默认"),
		@ApiImplicitParam(name = ProfileVOMeta.NOTES , value = "备注" , required = false , dataTypeClass=String.class , example = "默认 Profile 请勿删除"),
	})
	@ApiOperationSupport( order=4 , ignoreParameters = { ProfileVOMeta.PAGE_INDEX , ProfileVOMeta.PAGE_SIZE , ProfileVOMeta.SEARCH_FIELD , ProfileVOMeta.FUZZY_FIELD , ProfileVOMeta.SEARCH_VALUE , ProfileVOMeta.DIRTY_FIELDS , ProfileVOMeta.SORT_FIELD , ProfileVOMeta.SORT_TYPE , ProfileVOMeta.IDS } )
	@NotNull(name = ProfileVOMeta.ID)
	@SentinelResource(value = ProfileServiceProxy.UPDATE , blockHandlerClass = { SentinelExceptionUtil.class } , blockHandler = SentinelExceptionUtil.HANDLER )
	@PostMapping(ProfileServiceProxy.UPDATE)
	public Result update(ProfileVO profileVO) {
		Result result=profileService.update(profileVO,SaveMode.DIRTY_OR_NOT_NULL_FIELDS,false);
		return result;
	}


	/**
	 * 保存sys_profile
	*/
	@ApiOperation(value = "保存sys_profile")
	@ApiImplicitParams({
		@ApiImplicitParam(name = ProfileVOMeta.ID , value = "ID" , required = true , dataTypeClass=String.class , example = "default"),
		@ApiImplicitParam(name = ProfileVOMeta.NAME , value = "名称" , required = false , dataTypeClass=String.class , example = "默认"),
		@ApiImplicitParam(name = ProfileVOMeta.NOTES , value = "备注" , required = false , dataTypeClass=String.class , example = "默认 Profile 请勿删除"),
	})
	@ApiOperationSupport(order=5 ,  ignoreParameters = { ProfileVOMeta.PAGE_INDEX , ProfileVOMeta.PAGE_SIZE , ProfileVOMeta.SEARCH_FIELD , ProfileVOMeta.FUZZY_FIELD , ProfileVOMeta.SEARCH_VALUE , ProfileVOMeta.DIRTY_FIELDS , ProfileVOMeta.SORT_FIELD , ProfileVOMeta.SORT_TYPE , ProfileVOMeta.IDS } )
	@NotNull(name = ProfileVOMeta.ID)
	@SentinelResource(value = ProfileServiceProxy.SAVE , blockHandlerClass = { SentinelExceptionUtil.class } , blockHandler = SentinelExceptionUtil.HANDLER )
	@PostMapping(ProfileServiceProxy.SAVE)
	public Result save(ProfileVO profileVO) {
		Result result=profileService.save(profileVO,SaveMode.DIRTY_OR_NOT_NULL_FIELDS,false);
		return result;
	}


	/**
	 * 获取sys_profile
	*/
	@ApiOperation(value = "获取sys_profile")
	@ApiImplicitParams({
		@ApiImplicitParam(name = ProfileVOMeta.ID , value = "主键" , required = true , dataTypeClass=String.class , example = "1"),
	})
	@ApiOperationSupport(order=6)
	@NotNull(name = ProfileVOMeta.ID)
	@SentinelResource(value = ProfileServiceProxy.GET_BY_ID , blockHandlerClass = { SentinelExceptionUtil.class } , blockHandler = SentinelExceptionUtil.HANDLER )
	@PostMapping(ProfileServiceProxy.GET_BY_ID)
	public Result<Profile> getById(String id) {
		Result<Profile> result=new Result<>();
		if(IConfigService.DEFAULT_PROFILE_ID.equals(id)) {
			result.message("不允许删除默认的 Profile");
			return result;
		}
		Profile profile=profileService.getById(id);
		result.success(true).data(profile);
		return result;
	}


	/**
	 * 批量获取sys_profile <br>
	 * 联合主键时，请自行调整实现
	*/
		@ApiOperation(value = "批量获取sys_profile")
		@ApiImplicitParams({
				@ApiImplicitParam(name = ProfileVOMeta.IDS , value = "主键清单" , required = true , dataTypeClass=List.class , example = "[1,3,4]")
		})
		@ApiOperationSupport(order=3)
		@NotNull(name = ProfileVOMeta.IDS)
		@SentinelResource(value = ProfileServiceProxy.GET_BY_IDS , blockHandlerClass = { SentinelExceptionUtil.class } , blockHandler = SentinelExceptionUtil.HANDLER )
	@PostMapping(ProfileServiceProxy.GET_BY_IDS)
	public Result<List<Profile>> getByIds(List<String> ids) {
		Result<List<Profile>> result=new Result<>();
		List<Profile> list=profileService.getByIds(ids);
		result.success(true).data(list);
		return result;
	}


	/**
	 * 查询sys_profile
	*/
	@ApiOperation(value = "查询sys_profile")
	@ApiImplicitParams({
		@ApiImplicitParam(name = ProfileVOMeta.ID , value = "ID" , required = true , dataTypeClass=String.class , example = "default"),
		@ApiImplicitParam(name = ProfileVOMeta.NAME , value = "名称" , required = false , dataTypeClass=String.class , example = "默认"),
		@ApiImplicitParam(name = ProfileVOMeta.NOTES , value = "备注" , required = false , dataTypeClass=String.class , example = "默认 Profile 请勿删除"),
	})
	@ApiOperationSupport(order=5 ,  ignoreParameters = { ProfileVOMeta.PAGE_INDEX , ProfileVOMeta.PAGE_SIZE } )
	@SentinelResource(value = ProfileServiceProxy.QUERY_LIST , blockHandlerClass = { SentinelExceptionUtil.class } , blockHandler = SentinelExceptionUtil.HANDLER )
	@PostMapping(ProfileServiceProxy.QUERY_LIST)
	public Result<List<Profile>> queryList(ProfileVO sample) {
		Result<List<Profile>> result=new Result<>();
		List<Profile> list=profileService.queryList(sample);
		result.success(true).data(list);
		return result;
	}


	/**
	 * 分页查询sys_profile
	*/
	@ApiOperation(value = "分页查询sys_profile")
	@ApiImplicitParams({
		@ApiImplicitParam(name = ProfileVOMeta.ID , value = "ID" , required = true , dataTypeClass=String.class , example = "default"),
		@ApiImplicitParam(name = ProfileVOMeta.NAME , value = "名称" , required = false , dataTypeClass=String.class , example = "默认"),
		@ApiImplicitParam(name = ProfileVOMeta.NOTES , value = "备注" , required = false , dataTypeClass=String.class , example = "默认 Profile 请勿删除"),
	})
	@ApiOperationSupport(order=8)
	@SentinelResource(value = ProfileServiceProxy.QUERY_PAGED_LIST , blockHandlerClass = { SentinelExceptionUtil.class } , blockHandler = SentinelExceptionUtil.HANDLER )
	@PostMapping(ProfileServiceProxy.QUERY_PAGED_LIST)
	public Result<PagedList<Profile>> queryPagedList(ProfileVO sample) {
		Result<PagedList<Profile>> result=new Result<>();
		PagedList<Profile> list=profileService.queryPagedList(sample,sample.getPageSize(),sample.getPageIndex());
		result.success(true).data(list);
		return result;
	}



	/**
	 * 导出 Excel
	 * */
	@SentinelResource(value = ProfileServiceProxy.EXPORT_EXCEL , blockHandlerClass = { SentinelExceptionUtil.class } , blockHandler = SentinelExceptionUtil.HANDLER )
	@RequestMapping(ProfileServiceProxy.EXPORT_EXCEL)
	public void exportExcel(ProfileVO  sample,HttpServletResponse response) throws Exception {
		try{
			//生成 Excel 数据
			ExcelWriter ew=profileService.exportExcel(sample);
			//下载
			DownloadUtil.writeToOutput(response,ew.getWorkBook(),ew.getWorkBookName());
		} catch (Exception e) {
			DownloadUtil.writeDownloadError(response,e);
		}
	}


	/**
	 * 导出 Excel 模板
	 * */
	@SentinelResource(value = ProfileServiceProxy.EXPORT_EXCEL_TEMPLATE , blockHandlerClass = { SentinelExceptionUtil.class } , blockHandler = SentinelExceptionUtil.HANDLER )
	@RequestMapping(ProfileServiceProxy.EXPORT_EXCEL_TEMPLATE)
	public void exportExcelTemplate(HttpServletResponse response) throws Exception {
		try{
			//生成 Excel 模版
			ExcelWriter ew=profileService.exportExcelTemplate();
			//下载
			DownloadUtil.writeToOutput(response, ew.getWorkBook(), ew.getWorkBookName());
		} catch (Exception e) {
			DownloadUtil.writeDownloadError(response,e);
		}
	}



	@SentinelResource(value = ProfileServiceProxy.IMPORT_EXCEL , blockHandlerClass = { SentinelExceptionUtil.class } , blockHandler = SentinelExceptionUtil.HANDLER )
	@RequestMapping(ProfileServiceProxy.IMPORT_EXCEL)
	public Result importExcel(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {

		//获得上传的文件
		Map<String, MultipartFile> map = request.getFileMap();
		InputStream input=null;
		for (MultipartFile mf : map.values()) {
			input=StreamUtil.bytes2input(mf.getBytes());
			break;
		}

		if(input==null) {
			return ErrorDesc.failure().message("缺少上传的文件");
		}

		List<ValidateResult> errors=profileService.importExcel(input,0,true);
		if(errors==null || errors.isEmpty()) {
			return ErrorDesc.success();
		} else {
			return ErrorDesc.failure().message("导入失败").data(errors);
		}
	}


}
